package com.diandian.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Description of UdpServer
 * Copyright 2017 Meorient, Inc. All rights reserved.
 *
 * @author yuancheng.li on 2018年03月22日
 */
public class UdpServer {

    private static final int BYTE_LEN = 1024;
    private static final int PORT = 1234;
    private static final String[] responseMsg = new String[]{
            "rpc", "dubbo", "netty", "redis"
    };
    private static byte[] buffer = new byte[BYTE_LEN];

    public static void main(String[] args) throws IOException {

        new UdpServer().init();

    }

    public void init() throws IOException {
        //byte buf[], int offset, int length

        DatagramSocket socket = new DatagramSocket(PORT);

        //接收消息,并返回
        DatagramPacket packet = new DatagramPacket(buffer, BYTE_LEN);

        for (int i = 0; i < 1000; i++) {

            socket.receive(packet);
            byte[] data = packet.getData();
            System.out.println("received msg==>" + new String(data, 0, packet.getLength()));

            String msg = responseMsg[i % 4];
            byte[] outBuffer = msg.getBytes();
            DatagramPacket outPacket = new DatagramPacket(outBuffer, outBuffer.length, packet.getSocketAddress());
            socket.send(outPacket);
        }

    }

}
